<!--整单提货 订单列详情-->
<template>
  <div class="contain">
    <detail-header :status="'请安排提货'" :id="todolist"></detail-header>
    <h2 class="form-tit-row">提货凭证上传({{imgLista.length}})
      <em class="ft12 gray">最多9张</em>
    </h2>
    <div class="form-wrap mb30">
      <div class="form-wrap-row">
        <ul class="pic-list cf">
          <template v-for="(item, index) in imgLista">
            <li>
              <img :src="item" @click="previewPic(index)">
              <i class="iconfont icon-del-black" @click="delImg(index)"></i>
            </li>
          </template>
          <div class="upload-btn" @click="getFlag()">
            <i class="iconfont icon-add"></i>
          </div>
        </ul>
      </div>
    </div>
    <div class="form-wrap mb30">
      <div class="form-wrap-row">
        <div class="line displayflex">
          <div class="label">备注</div>
          <div class="ipt flex1">
            <textarea type="text" placeholder="请输入备注" class="form-txtarea" v-model="remark"></textarea>
          </div>
        </div>
      </div>
    </div>
    <div class="detail-bottom">
      <div class="btn default" @click="$router.go(-1)">取消</div>
      <div class="btn" @click="OrderAcceptance()">提货完成</div>
    </div>
    <previewer :list="list" ref="previewer"></previewer>
  </div>
</template>

<script>
import detailHeader from '@/components/core/header/detail_header.vue';
import {Previewer} from 'vux';
export default {
  name: 'pickBill',
  components: {
    detailHeader,
    Previewer
  },
  data() {
    return {
      todolist: [],
      remark: '',
      imgRaw: null,
      imgLista: [],
      imgListabase:[],
      list:[],
    }
  },
  watch:{
    //新来的
    imgLista(val){
      var _this = this;
      this.creatList(_this.imgLista)
    },
  },
  created() {
    this.getdata();
  },
  computed:{
    guid(){
      return this.$route.query.id;
    }
  },
  mounted() {
    this.$nextTick(function() {

    })
  },
  methods: {
    creatList(val){
      this.list = [];
      for(var i = 0;i<val.length;i++){
        var obj = {
          src:val[i]
        }
        this.list.push(obj)
      }
    },
    getdata() {
      this.todolist = sessionStorage.item?JSON.parse(sessionStorage.item):'';
    },
    OrderAcceptance() {
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        Guid: this.guid,
        remark: this.remark,
        BuyerGUID: userinfo.StaffID,
        BuyerName: userinfo.Name,
        BillState: 'P09',
        type: '2',
        FeedbackGUID: '',
        FeedbackName: '',
        imgurla:self.imgListabase,
        goodsdetail:JSON.parse(sessionStorage.goodsitem)
      };
      this.Ajax.post('OrderAcceptance', query).then(function(resp) {
        if (resp.IsSuccess) {
          self.Toast({
            message: '提货成功',
          });
          self.$router.push({
            path: '/order/deliverygoodslist',
          })
        } else {
          self.Toast({
            message: '提货失败',
          });
        }
      });
    },
    getFlag: function() {
      var self = this;
      //modi by lxf
      var ua = navigator.userAgent.toLowerCase();
      if(ua.match(/MicroMessenger/i)=="micromessenger") //微信打开的
      {
        self.WEIXIN_uploadImg(self);
      } else {
        self.APP_uploadImg(self);
      }
    },

    WEIXIN_uploadImg: function(Obj){
      var self = Obj;
      let currentSize = this.imgLista.length;
      self.jWeixin.chooseImage({
        count: 9, // 默认9
        sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          if (self.imgLista.length + localIds.length > 9) {
            self.Toast({
              message: "最多上传9张图片."
            });
            return false;
          }
          localIds.forEach(li => {
            self.imgLista.push(li);
          });
          self.getLocalImgDataC(currentSize);
        }
      });
    },

    APP_uploadImg: function(Obj){
      var self = Obj;
      if (window.plus) {
          plusReady();
      } else {
          document.addEventListener('plusready', plusReady, false);
      }
      function plusReady() {
          plus.key.addEventListener('backbutton', function() {}, false);
      }
      var imgLen = self.imgLista.length;
      if(imgLen >= 9){
        plus.nativeUI.toast('最多只能选择9张图片');
      } else {
        var actionbuttons = [{ title: "拍照" }, { title: "相册选取" }];
        var actionstyle = { title: "选择照片", cancel: "取消", buttons: actionbuttons };
        plus.nativeUI.actionSheet(actionstyle, function(e) {
            if (e.index == 1) {
                getImage(self);
            } else if (e.index == 2) {
                galleryImg();
            }
        });
      }

      // 拍照 
      function getImage(self) {
        var cmr = plus.camera.getCamera();
        cmr.captureImage(function(p) {
            plus.io.resolveLocalFileSystemURL(p, function(entry) {
              var jsonStr = '{"files":["'+ entry.toLocalURL() +'"]}'
              self.imgRaw = JSON.parse(jsonStr);
              compressImage(0);
            }, function(e) {
                plus.nativeUI.toast("读取拍照文件错误：" + e.message);
            });
        }, function(e) {
        }, {
            filename: "_doc/camera/",
            index: 1
        });
      }

      //相册选取图片  
      function galleryImg() {
        plus.gallery.pick( function(e){
          self.imgRaw = e;
          compressImage(0);
        },function ( e ) {
          console.log("取消选择图片");
        },{
          filter:"image",
          multiple:true,
          maximum:(9 - imgLen),
          system:false,
          onmaxed:function(){
            plus.nativeUI.alert('最多只能选择9张图片');
          }
        },{
            filter: "image",
            multiple: true,
            system: false
          });
        }

      //压缩图片  
      function compressImage(num) {
        var e = self.imgRaw;
        if(!e.files[num]){
          self.imgRaw = null;
        } else {
          var ext = e.files[num].substr(e.files[num].lastIndexOf("."), e.files[num].length);
          var filename = (new Date()).valueOf().toString() + ext;
          var compName = "_doc/compressed/" + filename;
          var path = e.files[num];
          plus.zip.compressImage({
              src: path,//src: (String 类型 )压缩转换原始图片的路径  
              dst: compName,//压缩转换目标图片的路径  
              quality: 20,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100  
              overwrite: true,//overwrite: (Boolean 类型 )覆盖生成新文件  
              format: 'jpg',
          },
          function(event) {
            var fileReader = new plus.io.FileReader();
            fileReader.readAsDataURL(event.target);
            fileReader.onloadend = function(s) {
                  if (self.imgLista.length > 9) {
                    plus.nativeUI.toast("最多上传9张图片");
                    return;
                } else {
                    var picUrl = s.target.result.toString();
                    var dataimg = picUrl.split(',');
                    self.imgLista.push(picUrl);
                    self.imgListabase.push(dataimg[1]);
                    compressImage(num + 1);
                }
            }
          }, function(error) {
              plus.nativeUI.toast("压缩图片失败，请稍候再试");
          });
        }
      }
    },
    

    getLocalImgDataC: function(index) {
      var self = this;
      this.jWeixin.getLocalImgData({
        localId: self.imgLista[index], // 图片的localID
        success: function(res) {
          let localData = res.localData;
          if (window.__wxjs_is_wkwebview) {
             var imgbase64 = localData.substr(22,localData.length);
            self.imgLista.splice(index, 1, localData);
            self.imgListabase.push(imgbase64);
           
          } else {
            self.imgListabase.push(localData);
          }
          self.getLocalImgDataC(index + 1);
        }
      });
    },
    //预览图片
    previewPic: function(index) {
      this.$refs.previewer.show(index);
    },
    //删除图片
    delImg: function(index) {
      this.imgLista.splice(index, 1);
    },
  }
}
</script> 